package com.ruoyi.message.manage.controller;


import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.plus.web.controller.BasePlusController;
import com.ruoyi.common.core.plus.web.page.PageDto;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.domain.LoginUser;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.message.general.entity.MessageCountryTemplate;
import com.ruoyi.message.general.entity.MessageTemplate;
import com.ruoyi.message.manage.model.dto.ManageMessageTemplateDto;
import com.ruoyi.message.manage.model.vo.ManageMessageTemplateVo;
import com.ruoyi.message.manage.service.ManageMessageCountryTemplateService;
import com.ruoyi.message.manage.service.ManageMessageTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/message/messageTemplate")
@Api(tags = "消息模板")
public class ManageMessageTemplateController extends BasePlusController {

    @Autowired
    private ManageMessageTemplateService manageMessageTemplateService;
    @Autowired
    private ManageMessageCountryTemplateService manageMessageCountryTemplateService;

    /**
     * 查询消息模板列表
     */
    @PreAuthorize("@ss.hasPermi('message:message_template:list')")
    @GetMapping("/list")
    @ApiOperation(value = "分页")
    public TableDataInfo<ManageMessageTemplateVo.CommonVo> list(ManageMessageTemplateDto.CommonDto commonDto) {
        PageDto pageDto = startPage();
        Page<MessageTemplate> page = new Page(pageDto.getCurrentPage(), pageDto.getPageSize());
        if (pageDto.getOrderItem() != null) {
            page.addOrder(pageDto.getOrderItem());
        }
        MessageTemplate messageTemplate = Convert.convert(MessageTemplate.class, commonDto);
        page = manageMessageTemplateService.getByPage(page, messageTemplate);
        return getDataTable(page);
    }

    /**
     * 导出消息模板列表
     */
    @PreAuthorize("@ss.hasPermi('message:message_template:export')")
    //@Log(title = "消息模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出")
    public void export(HttpServletResponse response, ManageMessageTemplateDto.CommonDto commonDto) throws IOException {
        MessageTemplate messageTemplate = Convert.convert(MessageTemplate.class, commonDto);
        List<MessageTemplate> list = manageMessageTemplateService.getByList(messageTemplate);
        ExcelUtil<MessageTemplate> util = new ExcelUtil<MessageTemplate>(MessageTemplate.class);
        util.exportExcel(response, list, "messageTemplate");
    }

    /**
     * 获取消息模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('message:message_template:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "查看")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ManageMessageTemplateVo.CommonVo commonVo = Convert.convert(ManageMessageTemplateVo.CommonVo.class, manageMessageTemplateService.getById(id));
        return AjaxResult.success(commonVo);
    }

    /**
     * 新增消息模板
     */
    @PreAuthorize("@ss.hasPermi('message:message_template:add')")
    //@Log(title = "消息配置", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增")
    public R add(@RequestBody ManageMessageTemplateDto.CommonDto commonDto) {
        MessageTemplate messageTemplate = Convert.convert(MessageTemplate.class, commonDto);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        messageTemplate.setCreateBy(loginUser.getUsername());
        messageTemplate.setUpdateBy(loginUser.getUsername());
        if (!messageTemplate.getType().equals("sms")) {
            messageTemplate.setChannel(null);
        }
        manageMessageTemplateService.save(messageTemplate);
        return toAjax(1);
    }

    /**
     * 修改消息模板
     */
    @PreAuthorize("@ss.hasPermi('message:message_template:edit')")
    //@Log(title = "消息配置", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改")
    public R edit(@RequestBody ManageMessageTemplateDto.CommonDto commonDto) {
        MessageTemplate messageTemplate = Convert.convert(MessageTemplate.class, commonDto);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        messageTemplate.setCreateBy(loginUser.getUsername());
        messageTemplate.setUpdateBy(loginUser.getUsername());
        if (!messageTemplate.getType().equals("sms")) {
            messageTemplate.setChannel(null);
        }
        int update = manageMessageTemplateService.update(messageTemplate);
        LambdaUpdateWrapper<MessageCountryTemplate> messageCountryTemplateLambdaUpdateWrapper = Wrappers.lambdaUpdate(MessageCountryTemplate.class)
                .eq(MessageCountryTemplate::getTemplateId, messageTemplate.getId())
                .set(MessageCountryTemplate::getTemplateCode, messageTemplate.getCode());
        manageMessageCountryTemplateService.update(null, messageCountryTemplateLambdaUpdateWrapper);
        return toAjax(update);
    }

    /**
     * 删除消息模板
     */
    @PreAuthorize("@ss.hasPermi('message:message_template:remove')")
    //@Log(title = "消息配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除")
    public R remove(@PathVariable Long[] ids) {
        LambdaQueryWrapper<MessageTemplate> messageTemplateLambdaQueryWrapper = Wrappers.lambdaQuery(MessageTemplate.class).in(MessageTemplate::getId, ids);
        manageMessageTemplateService.delete(messageTemplateLambdaQueryWrapper);
        LambdaQueryWrapper<MessageCountryTemplate> messageCountryTemplateLambdaQueryWrapper = Wrappers.lambdaQuery(MessageCountryTemplate.class).in(MessageCountryTemplate::getTemplateId, ids);
        manageMessageCountryTemplateService.delete(messageCountryTemplateLambdaQueryWrapper);
        return toAjax(1);
    }

}
